﻿using System;
using System.Linq;
using EzDesk.DevHelper.DbMgr.Views;
using EzDesk.Utility.Log;
using System.Xml.Linq;
using System.Diagnostics;
using System.Windows.Forms;
using EzDesk.Core.Data;
using EzDesk.Core.Model;

namespace EzDesk.DevHelper.DbMgr.Presenters
{
    public class FeedMainPresenter : DbMgrPresenterBase
    {
        private IFeedMainView _view;

        public FeedMainPresenter(IFeedMainView view)
        {
            _view = view;
            _logView = view;
        }

        public void RefreshFeedList()
        {
            LogEx.TRACE("MainPresenter", "获取FEED列表");
            //获取Feed列表);
            using (var db = new EzDeskDatabaseContainer())
            {
                var feedList = db.FeedTemplateSet
                    .Select(p => new
                             {
                                 TemplateName = p.TemplateName,
                             })
                    .OrderBy(p=>p.TemplateName)
                    .ToList();

                LogEx.TRACE("MainPresenter", "获取FEED列表成功");
                //显示Feed列表
                _view.DisplayFeedTemplatesList(feedList);
            }

        }

        public string AddNewFeed()
        {
            LogEx.TRACE("MainPresenter", "增添FEED");

            var templateName = getNewTemplateName();

            using (var db = new EzDeskDatabaseContainer())
            {
                db.FeedTemplateSet.AddObject(
                    new FeedTemplate()
                    {
                        //todo..
                        Title = "",
                        Body = "",
                        TemplateName = templateName,
                        TemplateIconName = "",
                        Id = Guid.NewGuid(),
                        DefaultTypeValue = 0

                    });

                db.SaveChanges();
                LogEx.TRACE("MainPresenter", "增添FEED成功");
            }


            RefreshFeedList();

            return templateName;

        }




        public void DeleteFeed(string selectFeedName)
        {
            using (var db = new EzDeskDatabaseContainer())
            {
                LogEx.TRACE("MainPresenter", "删除FEED");
                var feed = db.FeedTemplateSet
                    .Where(p => p.TemplateName == selectFeedName);
                foreach (var item in feed)
                {
                    db.FeedTemplateSet.DeleteObject(item);
                }
                db.SaveChanges();

                LogEx.TRACE("MainPresenter", "删除FEED成功");

                RefreshFeedList();
            }

        }




        private string getNewTemplateName()
        {
            return "新Feed" + " " + DateTime.Now.Ticks;
        }




    }
}
